package com.yupi.yuoj.judege.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.judege.codesandbox.CodeSandbox;
import com.yupi.yuoj.judege.codesandbox.model.ExecuteCodeRequest;
import com.yupi.yuoj.judege.codesandbox.model.ExecuteCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @Description 远程代码沙箱（实际调用）
 * @Author JFeng
 * @Date 2023/10/14
 */
@Slf4j
@Service("REMOTE")
public class RemoteCodeSandboxImpl implements CodeSandbox {
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Value("${codesandbox.port}")
    private String sandboxServicePort;

    @Value("${codesandbox.ip}")
    private String sandboxServiceIp;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
//        String url = "http://47.97.121.222:8122/executeCode";
        String url = "http://" + sandboxServiceIp + ":" + sandboxServicePort + "/executeCode";
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .body(JSONUtil.toJsonStr(executeCodeRequest))
                .execute()
                .body();
        if (StringUtils.isBlank(responseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remote error, message = {" + responseStr + "}");
        }
        log.info("代码沙箱返回：--->" + responseStr);
        ExecuteCodeResponse response = JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
        return response;
    }
}
